package com.example.androidframework.ui.course.thread

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.AsyncTask
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.os.Message
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.androidframework.R
import com.martin.lib_base.ktx.loge
import com.martin.lib_base.ktx.logi
import com.martin.lib_base.ktx.logw
import com.martin.lib_base.ktx.normalToast
import java.lang.Thread.sleep
import kotlin.concurrent.thread

class ThreadTestActivity : AppCompatActivity() {
    val workHandler by lazy {
        // 必须在mainLooper中更新UI,否则会报错
        Handler(mainLooper) {
            logw("handleMessage-当前线程: ${Thread.currentThread().name}")
            when (it.what) {
                200 -> textView.text = it.obj.toString()
            }
            false
        }
    }

    // 异步任务: 已废弃,不推荐使用
    val asyncTask by lazy {
        object : AsyncTask<Void, Void, String>() {
            @Deprecated("Deprecated in Java")
            override fun doInBackground(vararg params: Void?): String {
                return "ZhangSan"
            }

            @SuppressLint("StaticFieldLeak")
            @Deprecated("Deprecated in Java")
            override fun onPostExecute(result: String?) {
                textView.text = result
            }
        }.execute()
    }

    lateinit var textView: TextView
    lateinit var button: Button

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_thread_test)
        textView = findViewById<TextView>(R.id.text)
        button = findViewById<Button>(R.id.button)

        button.setOnClickListener {
            handlerTest()
        }

        handlerThreadTest()

        findViewById<Button>(R.id.button_handler_thread).setOnClickListener {
            // 主线程中向mHandlerThread子线程发送消息
            val msg = Message()
            msg.what = 1
            mHandlerInHandlerThread.sendMessage(msg)
        }

        findViewById<Button>(R.id.button_handler_thread_quit).setOnClickListener {
            // 退出HandlerThread子线程
            mHandlerThread.quit()
            normalToast("退出HandlerThread子线程")
        }
    }

    // HandlerThread主要实现主线程到子线程的通信
    // 创建HandlerThread对象，即创建了一个新的线程，参数为线程名，仅仅是标记线程用的
    val mHandlerThread = HandlerThread("mHandlerThread")
    lateinit var mHandlerInHandlerThread: Handler

    private fun handlerThreadTest() {
        mHandlerThread.start()
        mHandlerInHandlerThread = Handler(mHandlerThread.looper) {
            logw("mHandlerInHandlerThread-当前线程: ${Thread.currentThread().name}")
            // 已经是在子线程mHandlerThread中运行了
            try {
                sleep(3000)
            } catch (e: Exception) {
                loge("e.message === ${e.message}")
            }

            // 子线程向主线程通信
            val msg = Message()
            msg.what = 200
            msg.obj = "从mHandlerInHandlerThread发送过来的消息"
            workHandler.sendMessage(msg)

            false
        }
    }

    // Handler消息机制
    // 常用于子线程向主线程的通信,例如更新UI
    private fun handlerTest() {
        // 开启子线程
        thread {
            logw("sendMessage-当前线程: ${Thread.currentThread().name}")
            logi("先沉睡3秒")
            sleep(3000)
            logi("沉睡结束")

            val msg = Message()
            msg.what = 200
            msg.obj = "通过Handler发送的消息"
            workHandler.sendMessage(msg)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 退出消息循环
        mHandlerThread.quit()
        workHandler.removeCallbacks {
            // 防止Handler内存泄露 清空消息队列
        }
    }

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, ThreadTestActivity::class.java)
            context.startActivity(intent)
        }
    }
}